//
//  FindInfoViewController.swift
//  tree_ai
//
//  Created by oldmacbook on 2024/5/25.
//

import UIKit
import Alamofire
import AlamofireImage
import ProgressHUD



class FindInfoViewController: UIViewController {
    var localTreeId: Int64?
    var oneTree: Tree?
    //var treeName: String?
    //var imageUrl: String?
    var contentBuffer: NSMutableString?
    
    var isOutputing: Bool = false
    //var titleLabel: UILabel?
    
    var contentScrollView: UIScrollView?
    var contentLabel: UILabel?
    
    var treeImageView: UIImageView?
    
    
    var aiRequest: DataStreamRequest?
    
    
    let titleFilters: [(String, String)] = [("图中的主要植物是", ""),
                                            ("图中的主要植物为",""),
                                            ("图中最主要的植物是",""),
                                            ("图中最主要的植物",""),
                                            ("植物名称：",""),
                                            ("#",""),
                                            ("\n",""),
                                            ("*",""),
                                            ("图中主要的动物是",""),
                                            ("图中的主要动物是",""),
    ]
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
            
        self.initialize()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        self.initialize()
    }
    
    init() {
        super.init(nibName: nil, bundle: nil)

        self.initialize()
    }
    
    func initialize() {
        // 你的初始化代码
        self.hidesBottomBarWhenPushed = true
    }


    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        
//        let file_name = "fe35f4351819e86fcfbeb5156d117825.jpg"
//        let image_url = "https://sfile.chatglm.cn/chatglm4/66d93c84-8611-45ef-b600-61224e3f2fd1.jpg"
//        let image_id = "chatglm4/66d93c84-8611-45ef-b600-61224e3f2fd1.jpg"
//        let image_file_size = Int64(0)
        
        //let rowId = TreeSqlManager.shared.insertTree(image_name: file_name, image_url: image_url, image_id: image_id, image_file_size: image_file_size)
        //localTreeId = 1
        
        oneTree = TreeSqlManager.shared.getOneTree(id: localTreeId!)
        print("oneTree:\(oneTree)")
        
        
        self.contentBuffer = NSMutableString(string: (self.oneTree?.desc)!)
        
        self.createView()
        
        
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.updateContentLabel()
        if self.oneTree?.desc == "" {
            self.streamTest()
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    func createView() {
        self.view.backgroundColor = .brown
        
        let backButton = UIBarButtonItem(title: "< 返回", style: .plain, target: self, action: #selector(handleBackButton))
        navigationItem.leftBarButtonItem = backButton
        
        let testBtn = UIButton()
        self.view.addSubview(testBtn)
        testBtn.setTitle("AI识别", for: .normal)
        testBtn.setTitleColor(.blue, for: .normal)
        testBtn.snp.makeConstraints { make in
            make.top.equalTo(120)
            make.left.equalTo(30)
            make.width.equalTo(100)
            make.height.equalTo(40)
        }
        testBtn.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
        
        
        treeImageView = UIImageView()
        treeImageView?.backgroundColor = .gray
        self.view.addSubview(treeImageView!)
        treeImageView?.snp.makeConstraints { make in
            make.top.equalTo(100)
            make.centerX.equalTo(self.view.center)
            make.width.equalTo(120)
            make.height.equalTo(120)
        }
        
        let urlStr = oneTree?.image_url
        
        treeImageView?.af.setImage(withURL: URL(string: urlStr!)!)
        
        contentScrollView = UIScrollView()
        self.view.addSubview(contentScrollView!)
        contentScrollView?.backgroundColor = .lightGray
        contentScrollView?.snp.makeConstraints({ make in
            make.top.equalTo(treeImageView!.snp_bottomMargin).offset(10)
            make.left.equalTo(5)
            make.right.equalTo(-5)
            make.bottom.equalTo(-15)
        })
        
        contentLabel = UILabel()
        contentLabel?.font = UIFont.systemFont(ofSize: 14)
        contentLabel?.textColor = .black
        contentLabel?.numberOfLines = 0
        contentScrollView?.addSubview(contentLabel!)
        contentLabel?.snp.makeConstraints({ make in
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.bottom.equalTo(0)
            make.width.equalTo(0)
            //make.right.equalTo(0)
        })
    }
    
    @objc func handleBackButton() {
        // 这里实现你的返回拦截逻辑
        if self.isOutputing {
            let alertController = UIAlertController(title: "您确定要返回吗？", message: "正在生成内容，返回将中断消息", preferredStyle: .alert)
            
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            let okAction = UIAlertAction(title: "确定", style: .default) { _ in
                // 用户点击了确定，执行返回操作
                self.aiRequest?.cancel()
                self.navigationController?.popViewController(animated: true)
            }
            
            alertController.addAction(cancelAction)
            alertController.addAction(okAction)
            
            present(alertController, animated: true, completion: nil)
        } else {
            self.navigationController?.popViewController(animated: true)
        }

    }
    
    func updateContentLabel() {
        
        let labelW = contentScrollView?.frame.size.width
        
        contentLabel?.snp.updateConstraints({ make in
            make.width.equalTo(labelW!)
        })
        
        let fullString = String(self.contentBuffer!)
        self.contentLabel?.text = fullString
        oneTree?.desc = fullString
        self.contentLabel?.sizeToFit()
        
        let labelH = self.contentLabel?.frame.size.height
        
        self.contentScrollView?.contentSize = CGSize(width: labelW!, height: labelH!+20)
        
        var cOffsetY = labelH! - (contentScrollView?.frame.size.height)! + 10
        if cOffsetY < 0 {
            cOffsetY = 0
        }
        self.contentScrollView?.setContentOffset(CGPoint(x: 0, y: cOffsetY), animated: true)
        
        var seqBeginStr = ""
        let seqEndStrs = [",", "，", ".", "。","\n"]
        if self.oneTree?.category=="botany"{
            seqBeginStr = "植物是"
        
        }else if self.oneTree?.category=="animal" {
            seqBeginStr = "动物是"

        }
        var treeName = ""
        
        if let beginIndex = fullString.range(of: seqBeginStr) {
            let substringAfterBegin = fullString[beginIndex.upperBound...]
            var earliestEndIndex: String.Index?
            for seqEndStr in seqEndStrs {
                if let endIndex = substringAfterBegin.range(of: seqEndStr) {
//                    let indexBeforeEnd = substringAfterBegin.index(before: endIndex.lowerBound)
//                    treeName = String(substringAfterBegin[..<indexBeforeEnd])
//                    treeName = String(treeName.dropLast())
//                    break
                    if earliestEndIndex == nil || endIndex.upperBound < earliestEndIndex! {
                        earliestEndIndex = endIndex.upperBound
                    }
                }
            }
            if let endIndex = earliestEndIndex {
                let indexBeforeEnd = substringAfterBegin.index(before: endIndex)
                treeName = String(substringAfterBegin[..<indexBeforeEnd])
            }

            
        }

        
        //let elems = fullString.substring(to: <#T##String.Index#>)
        //if findpos?.lowerBound. > 0 {
        
        if treeName == "" {
            
        }else{

            if treeName.count > 25 {
                treeName = String(treeName.prefix(25))
            }
            oneTree?.name = treeName
            self.navigationItem.title = treeName
        }
        
        
        //}
        
        
        
        
    }
    
    
    @objc func buttonTapped() {
        if !self.isOutputing {
            
            self.streamTest()
        }
        
    }
    
    
    func streamTest() {
        self.isOutputing = true
        //ProgressHUD.animate("AI加速...")
        ProgressHUD.show("AI加速...", interaction: false)
        
        self.contentBuffer?.setString("")
        var url = "http://127.0.0.1:8080/test_stream"
        
        url = "http://47.113.124.135:8080/test_stream"

        
        //AF.streamRequest(url, method: ,parameters: <#T##Parameters?#>)
        let params: [String: String] = [
            "category": self.oneTree!.category,
            "file_name": self.oneTree!.image_name,
            "file_id": self.oneTree!.image_id,
            "image_url": self.oneTree!.image_url
        ]
        
        let enco = JSONParameterEncoder.default
       
        
        self.aiRequest = AF.streamRequest(url, method: .post, parameters: params, encoder: enco, headers: nil , automaticallyCancelOnStreamError: true, interceptor: nil, requestModifier: nil).responseStreamString{ response in
            if let data = response.value {
                //print("datatype:\(type(of: data))")
                //print("received \(data.count) bytes")
                if data.count > 0 {
                    //
                    if data == "stream_api_finished" {
                        let fullString = String(self.contentBuffer!)
                        print("fullString:", fullString)
                        ProgressHUD.showSucceed("AI识别完毕", interaction: false, delay: 1.0)
                        //ProgressHUD.succeed("AI识别完毕")
                        self.isOutputing = false
                    }else if data == "stream_api_failed" {
                        //ProgressHUD.failed("AI请求失败", delay: 2.0)
                        ProgressHUD.showFailed("AI请求失败", interaction: false, delay: 2.0)
                        self.isOutputing = false
                    }else {
                        //print("received:", data)
                        ProgressHUD.dismiss()
                        self.contentBuffer?.append(data)
                        
                    }
                    
                    self.updateContentLabel()
                    // process received data here
                    TreeSqlManager.shared.updateTree(id: self.localTreeId!, name: (self.oneTree?.name)!, desc: (self.oneTree?.desc)!)
                }
                
            }
        }
        
        
        
    }

}
